<template>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="患者编号" prop="patId">
            <el-input v-model="formData.patId" placeholder="请输入患者编号" @input="getRentInfoByPatId" />
          </el-form-item>
          <el-form-item label="患者名称" prop="patName">
            <el-input v-model="formData.patName" placeholder="请输入患者名称" />
          </el-form-item>
          <el-form-item label="患者描述" prop="patDeptDesc">
            科室: {{formData.patDetails?.deptDesc}} 病区: {{formData.patDetails?.wardDesc}} 床位: {{formData.patDetails?.bedNo}}
          </el-form-item>
          <el-form-item label="录入时间" prop="entryTime">
            <el-date-picker
                v-model="formData.entryTime"
                type="date"
                value-format="x"
                placeholder="选择录入时间"
            />
          </el-form-item>
          <el-form-item label="干扰数" prop="interference">
            <el-input v-model="formData.interference" placeholder="请输入干扰数" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备编号" prop="devId">
            <el-input v-model="formData.devId" placeholder="请输入设备编号" @input="getRentInfoByDevId" />
          </el-form-item>
          <el-form-item label="设备描述" prop="">
            {{formData.brand + "&nbsp;&nbsp;" + formData.model}}
          </el-form-item>
          <el-form-item label="装拆机时间" prop="returnTime">
            <el-date-picker
                v-model="formData.rentTime"
                type="date"
                value-format="x"
                placeholder="选择装机时间"
                :readonly="true"
                style="width:150px"
            />
            {{"-"}}
<!--            {{"&nbsp;&nbsp;"}}-->
            <el-date-picker
                v-model="formData.returnTime"
                type="date"
                value-format="x"
                placeholder="选择拆机时间"
                :readonly="true"
                style="width:150px"
            />
          </el-form-item>
          <el-form-item label="基线粗" prop="baseline">
            <el-switch
                v-model="formData.baseline"
                :active-value="1"
                :inactive-value="0"
            />
          </el-form-item>
          <el-form-item label="脱落" prop="detachment">
            <el-switch
                v-model="formData.detachment"
                :active-value="1"
                :inactive-value="0"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-row>
    </el-form>
    <el-button @click="submitForm" type="primary" :disabled="formLoading">录入完成</el-button>
    <el-button @click="resetForm()">重 置</el-button>
<!--    <el-button @click="loseDismantle" :disabled="formLoading">遗 失</el-button>-->

  <!-- 医生拆机列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true" @row-click="onRowClick" >
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="录入情况" align="center" prop="lost" >
        <template #default="scope">
          <span v-if="scope.row.jobType === 25">"已录入"</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="作业类型" align="center" prop="jobType" />-->
<!--      <el-table-column label="医生编号" align="center" prop="docId" />-->
      <el-table-column label="医生名称" align="center" prop="docName" />
      <el-table-column label="设备编号" align="center" prop="devId" />
      <el-table-column label="患者编号" align="center" prop="patId" />
      <el-table-column label="患者名称" align="center" prop="patName" />
      <el-table-column
          label="作业时间"
          align="center"
          prop="jobTime"
          :formatter="dateFormatter"
          width="180px"
      />
      <el-table-column label="作业概要" align="center" prop="summary" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          :formatter="dateFormatter"
          width="180px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
              link
              type="primary"
              @click="openForm('update', scope.row.id)"
              v-hasPermi="['ecg:job-record:update']"
          >
            编辑
          </el-button>
          <el-button
              link
              type="danger"
              @click="handleDelete(scope.row.id)"
              v-hasPermi="['ecg:job-record:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
  </ContentWrap>

</template>

<script setup lang="ts">
import { DevRentApi, DevRentVO } from '@/api/ecg/devrent'
import {dateFormatter} from "@/utils/formatTime";
import {JobRecordApi, JobRecordVO} from "@/api/ecg/jobrecord";
import {isStringEmpty} from "@/utils/stringUtil";
import {curDayEnd, curDayStart} from "@/utils/dateUtil";

/** 装机拆机 表单 */
defineOptions({ name: 'DevDataEntry' })

const emit = defineEmits(['success-dataEntry']) // 定义 success 事件，用于操作成功后的回调

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示

const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用

const formData = ref({})

const formRules = reactive({
  // devId: [{ required: true, message: '设备编号不能为空', trigger: 'blur' }],
  entryTime: [{ required: true, message: '请选择录入日期', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as DevRentVO
    await DevRentApi.devDataEntry(data)
    message.success(t('操作成功'))
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success-dataEntry')
    resetForm()
    getList()
  } finally {
    formLoading.value = false
  }
}

// 遗失操作
/*
const loseDismantle = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as DevRentVO
    await DevRentApi.devLose(data)
    message.success(t('操作成功'))
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success-dataEntry')
    resetForm()
    getList()
  } finally {
    formLoading.value = false
  }
}
*/

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    devId: undefined,
    patId: undefined,
    patName: undefined,
    patDeptCode: undefined,
    patDeptDesc: undefined,
    patWardCode: undefined,
    patWardDesc: undefined,
    patBedNo: undefined,
    rentTime: undefined,
    returnTime: undefined,
    entryTime: new Date().getTime(),
    interference: undefined,
    baseline: undefined,
    detachment: undefined,
    remark: undefined,
    category: '',
    brand: '',
    model: '',
  }
  formRef.value?.resetFields()
}

const getRentInfoByDevId = () => {
  const tempDevId = formData.value.devId;
  resetForm()
  if (isStringEmpty(tempDevId))
    return

  formData.value.devId = tempDevId;
  getRentInfo()
}

const getRentInfoByPatId = () => {
  const tempPatId = formData.value.patId;
  resetForm()
  if (isStringEmpty(tempPatId))
    return

  formData.value.patId = tempPatId;
  getRentInfo()
}

const getRentInfo = async () => {
  const data = await DevRentApi.getDismantledRent(formData.value)
  if (null === data)
    return

  formData.value = data
  if (data.entryTime === null)
    data.entryTime = new Date().getTime()
}


const loading = ref(true) // 列表的加载中
const list = ref<JobRecordVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  jobType: [25],
  docId: undefined,
  docName: undefined,
  devId: undefined,
  patId: undefined,
  patName: undefined,
  jobTime: [curDayStart(), curDayEnd()],
  summary: undefined,
  remark: undefined,
  createTime: []
})
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await JobRecordApi.getJobRecordDoctorPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const onRowClick = (cur) => {
  if (cur !== null)
    getSelectedRent( cur.rentId )
}

const getSelectedRent = async (rentId) => {
  formData.value = await DevRentApi.getDevRent(rentId)
}

/** 初始化 **/
onMounted(() => {
  resetForm()
  getList()
})

</script>
